﻿using System.Collections.ObjectModel;
using RiskMan.Config;
using RiskMan.DataClass.Models;
using RiskMan.DataClass.Models.Gilevskiy;
using RiskMan.DataClass.Models.NotBasModels;
using RiskMan.Views.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Ciloci.Flee;

namespace RiskMan.Views.Gilevskiy
{
    /// <summary>
    /// Interaction logic for addNewRobot.xaml
    /// </summary>
    public partial class AddNewRobot : Window
    {
        private RobotGilevskiyItem robotGilevskiyItem;
        private DataClass.Data data;
        List<Trade> trades;
        public AddNewRobot(RobotGilevskiyItem item, DataClass.Data data)
        {
            InitializeComponent();
            robotGilevskiyItem = item;
            this.data = data;
            trades = data.GetTradeList();


            #region Счет
            CmbxClientCode.ItemsSource = trades.Select(a => a.ClientCode).ToList();
            for (int i = 0; i < CmbxClientCode.Items.Count; i++)
            {
                if (CmbxClientCode.Items[i].ToString() == robotGilevskiyItem.ClientCode)
                    CmbxClientCode.SelectedIndex = i;
            }
            #endregion

            #region Тип Сделки
            CmbxTypeDeal.ItemsSource = new List<string>() { Cfg.Buy, Cfg.Sell };
            CmbxTypeDeal.SelectedIndex = 0;
            if (robotGilevskiyItem.Operation != null)
                CmbxTypeDeal.SelectedValue = robotGilevskiyItem.Operation;
            #endregion

            #region Seccode
            CmbxInstrument.ItemsSource = data.GetSeccodeList();
            for (int i = 0; i < CmbxInstrument.Items.Count; i++)
            {
                if (CmbxInstrument.Items[i].ToString() == robotGilevskiyItem.Instrument)
                    CmbxInstrument.SelectedIndex = i;
            }
            #endregion

            TxbxQuantity.Text = robotGilevskiyItem.Quantity.ToString();
            TxbxCondition.Text = robotGilevskiyItem.Condition;
            TxbxComment.Text = robotGilevskiyItem.Comment;
            TxbxConditionDitgit.Text = robotGilevskiyItem.ResultConditionDitgit;
        }




        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        private void ButtonAccept_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (CmbxClientCode.SelectedIndex >= 0)
                {
                    robotGilevskiyItem.ClientCode = CmbxClientCode.SelectedValue.ToString();
                    List<Trade> tradeList = data.GetTradeList();
                    if (tradeList != null)
                        for (int i = 0; i < tradeList.Count; i++)
                            if (tradeList[i].ClientCode == robotGilevskiyItem.ClientCode)
                                robotGilevskiyItem.Account = tradeList[i].Account;
                }
                else
                {
                    new DialogOkCancel("Выберите код клиента(счет)!", "Ошибка добавления");
                    return;
                }

                if (CmbxTypeDeal.SelectedIndex >= 0)
                    robotGilevskiyItem.Operation = CmbxTypeDeal.SelectedValue.ToString();
                else
                {
                    new DialogOkCancel("Выберите вид операции!", "Ошибка добавления");
                    return;
                }

                if (CmbxInstrument.SelectedIndex >= 0)
                    if (CmbxInstrument.SelectedValue.ToString() != "Не выбран")
                        robotGilevskiyItem.Instrument = CmbxInstrument.SelectedValue.ToString();
                    else
                    {
                        new DialogOkCancel("Выберите торгуемый инструмент!", "Ошибка добавления");
                        return;
                    }
                else
                {
                    new DialogOkCancel("Выберите торгуемый инструмент!", "Ошибка добавления");
                    return;
                }

                robotGilevskiyItem.Quantity = Convert.ToInt32(TxbxQuantity.Text);
                robotGilevskiyItem.Condition = TxbxCondition.Text;

                try
                {
                    ExpressionContext context = new ExpressionContext();
                    context.Imports.AddType(typeof(Math));
                    LogikConditionToDitgit logik = new LogikConditionToDitgit();
                    robotGilevskiyItem.ResultConditionDitgit= logik.ConvertConditionFromStringToDitgit(robotGilevskiyItem);

                    IGenericExpression<bool> eGeneric = context.CompileGeneric<bool>(robotGilevskiyItem.ResultConditionDitgit);

                    TxbxConditionDitgit.Text = robotGilevskiyItem.ResultConditionDitgit;
                    robotGilevskiyItem.ResultCondition= eGeneric.Evaluate();
                }
                catch 
                {
                    new DialogOkCancel("Не верно введены условия", "Ошибка условия");
                    return; 
                }
                

                robotGilevskiyItem.Comment = TxbxComment.Text;
                robotGilevskiyItem.GuidItem = Guid.NewGuid();
                robotGilevskiyItem.TradeList = new ObservableCollection<TradesOpen>();

                DialogResult = true;
                Close();
            }
            catch
            { }
        }


        #region Обработка получение текстобксом фокуса и потери его, замена запятой на точку

        private void TxbxLostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                ((TextBox)sender).Text = 0.ToString();

            char pointChar = ',';
            string str = (1.2).ToString();
            if (str.IndexOf('.') > 0) pointChar = '.';

            if (pointChar == ',')
                ((TextBox)sender).Text = ((TextBox)sender).Text.Replace('.', pointChar);

            if (pointChar == '.')
                ((TextBox)sender).Text = ((TextBox)sender).Text.Replace(',', pointChar);


        }

        private void TxbxGotFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (((TextBox)sender).Text != "")
                {
                    if (Convert.ToDouble(((TextBox)sender).Text) == 0)
                    {
                        ((TextBox)sender).Text = "";
                    }
                }
            }
            catch
            {
                ((TextBox)sender).Text = "";
            }
        }

        private void TxbxPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;

            if ((e.Text.IndexOf('.') == 0 || e.Text.IndexOf(',') == 0) && ((TextBox)sender).Text.IndexOf('.') == -1 && ((TextBox)sender).Text.IndexOf(',') == -1)
                e.Handled = false;
        }

        private void TxbxDitgitPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;
        }
        #endregion

        private void TxbxCondition_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                ExpressionContext context = new ExpressionContext();
                context.Imports.AddType(typeof(Math));
                LogikConditionToDitgit logik = new LogikConditionToDitgit();
                robotGilevskiyItem.ResultConditionDitgit = logik.ConvertConditionFromStringToDitgit(TxbxCondition.Text, CmbxInstrument.SelectedItem.ToString());
                TxbxConditionDitgit.Text = robotGilevskiyItem.ResultConditionDitgit;

            }
            catch
            {

            }
        }
    }
}
